<template>
  <div id="userLayout">
    <div class="login_panle">
      <div class="login_panle_form">
        <div class="login_panle_form_title">
          <img
            v-if="userStore.confMap.assetsUrl"
            class="login_panle_form_title_logo"
            :src="`${userStore.confMap.assetsUrl}/logo.png`"
            alt
          />
          <!-- <p class="login_panle_form_title_p">{{ $GIN_VUE_ADMIN.appName }}</p> -->
        </div>
        <el-form
          ref="loginForm"
          :model="loginFormData"
          :rules="rules"
          @keyup.enter="submitForm"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginFormData.username"
              placeholder="请输入用户名"
            >
              <template #suffix>
                <span class="input-icon">
                  <el-icon>
                    <user />
                  </el-icon>
                </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginFormData.password"
              :type="lock === 'lock' ? 'password' : 'text'"
              placeholder="请输入密码"
            >
              <template #suffix>
                <span class="input-icon">
                  <el-icon>
                    <component :is="lock" @click="changeLock" />
                  </el-icon>
                </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item style="position: relative" prop="captcha">
            <el-input
              v-model="loginFormData.captcha"
              placeholder="请输入验证码"
              style="width: 60%"
            />
            <div class="vPic">
              <img
                v-if="picPath"
                :src="picPath"
                alt="请输入验证码"
                @click="loginVerify()"
              />
            </div>
          </el-form-item>
          <el-form-item>
            <!-- <el-button
              type="primary"
              style="width: 46%"
              @click="checkInit"
            >前往初始化</el-button> -->
            <el-button type="primary" style="width: 100%" @click="submitForm"
              >登 录</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <!-- <div class="login_panle_right" /> -->
      <div class="login_panle_foot" >
        <div class="links" v-if="!userStore.confMap.oemEnable">
          <a href="https://smartide.cn/zh/docs/" target="_blank">
            <img src="@/assets/docs.png" class="link-icon" />
          </a>
          <a
            href="https://gitee.com/organizations/smartide/issues"
            target="_blank"
          >
            <img src="@/assets/kefu.png" class="link-icon" />
          </a>
          <a href="https://github.com/SmartIDE/" target="_blank">
            <img src="@/assets/github.png" class="link-icon" />
          </a>
          <a href="https://space.bilibili.com/1001970523" target="_blank">
            <img src="@/assets/video.png" class="link-icon" />
          </a>
        </div>
        <div class="copyright">
          <bootomInfo />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login'
}
</script>

<script setup>
import { captcha } from '@/api/user'
import { checkDB } from '@/api/initdb'
import bootomInfo from '@/view/layout/bottomInfo/bottomInfo.vue'
import { ElLoading, ElMessage } from 'element-plus'
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { initDB } from '@/api/initdb'
import { useUserStore } from '@/pinia/modules/user'

const router = useRouter()
// 验证函数
const checkUsername = (rule, value, callback) => {
  if (value.length < 5) {
    return callback(new Error('请输入正确的用户名'))
  } else {
    callback()
  }
}
const checkPassword = (rule, value, callback) => {
  if (value.length < 6) {
    return callback(new Error('请输入正确的密码'))
  } else {
    callback()
  }
}

// 获取验证码
const loginVerify = () => {
  captcha({}).then((ele) => {
    rules.captcha[1].max = ele.data.captchaLength
    rules.captcha[1].min = ele.data.captchaLength
    picPath.value = ele.data.picPath
    loginFormData.captchaId = ele.data.captchaId
  })
}
loginVerify()

// 登录相关操作
const lock = ref('lock')
const changeLock = () => {
  lock.value = lock.value === 'lock' ? 'unlock' : 'lock'
}
const form = reactive({
  dbType: 'mysql',
  host: 'gva-mysql',
  port: '3306',
  userName: 'root',
  password: 'smartide@1024',
  dbName: 'gva'
})
const initMysqlDB = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在初始化数据库，请稍候',
    spinner: 'loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    let password = '$(DBPassword)'
    if (password != 'smartide@1024' && password != '$(DBPassword)') {
      form.password = password
    }
    const res = await initDB(form)
    if (res.code === 0) {
      out.value = true
      ElMessage({
        type: 'success',
        message: res.msg
      })
      // router.push({ name: 'Login' })
    }
    loading.close()
  } catch (err) {
    loading.close()
  }
}
const loginForm = ref(null)
const picPath = ref('')
const loginFormData = reactive({
  username: '',
  password: '',
  captcha: '',
  captchaId: ''
})
const rules = reactive({
  username: [{ validator: checkUsername, trigger: 'blur' }],
  password: [{ validator: checkPassword, trigger: 'blur' }],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    {
      message: '验证码格式不正确',
      trigger: 'blur'
    }
  ]
})

const userStore = useUserStore()

const login = async () => {
  return await userStore.LoginIn(loginFormData)
}
const getWebConf = async () => {
  return await userStore.getWebConf()
}
const submitForm = () => {
  loginForm.value.validate(async (v) => {
    if (v) {
      const flag = await login()
      if (!flag) {
        loginVerify()
      }
    } else {
      ElMessage({
        type: 'error',
        message: '请正确填写登录信息',
        showClose: true
      })
      loginVerify()
      return false
    }
  })
}

// 跳转初始化
const checkInit = async () => {
  const res = await checkDB()
  if (res.code === 0) {
    if (res.data?.needInit) {
      // userStore.NeedInit()
      initMysqlDB()
    } else {
      ElMessage({
        type: 'info',
        message: '已配置数据库信息，无法初始化'
      })
    }
  }
}

onMounted(async () => {
  //await checkInit()
  await getWebConf()
})
</script>

<style lang="scss" scoped>
@import '@/style/newLogin.scss';
</style>
